// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: jhkim

#pragma once

#include <string>
#include <utility>
#include <vector>
#include "coin2/base/time.h"

namespace coin2::strategy::linear_model {

namespace detail {

inline int64_t hhmmss_to_ts(const std::string& hhmmss) {
  CHECK_EQ(hhmmss.size(), 6) << hhmmss;
  int64_t hh = std::stoll(hhmmss.substr(0, 2));
  int64_t mm = std::stoll(hhmmss.substr(2, 2));
  int64_t ss = std::stoll(hhmmss.substr(4, 2));
  return (((hh * 60) + mm) * 60 + ss) * 1e9;
}

}  // namespace detail


class HaltManager {
 public:
  explicit HaltManager(const HaltConfig& halt_config) {
    CHECK_EQ(halt_config.hhmmss_size(), halt_config.duration_ns_size());
    for (int i = 0; i < halt_config.hhmmss_size(); ++i) {
      int64_t begin_ts = detail::hhmmss_to_ts(halt_config.hhmmss(i));
      int64_t duration = halt_config.duration_ns(i);
      begin_end.push_back(std::make_pair(begin_ts, begin_ts + duration));
    }
  }

  void UpdateTime(int64_t fetched_time) {
    if (begin_end.empty()) return;
    current_time = fetched_time;
    if (today_utc0 + 24 * 3600 * 1e9 < current_time) {
      today_utc0 = TimestampToUtc0(current_time);
    }
    int64_t today_time_since_utc0 = current_time - today_utc0;
    bool halt_iter = false;
    for (const auto& [begin, end] : begin_end) {
      if (begin < today_time_since_utc0 && today_time_since_utc0 < end) {
        halt_iter = true;
      }
    }
    if (halt_iter != halt) {
      LOG(INFO) << "HALT STATUS "
          << halt << " -> " << halt_iter << " at " << today_time_since_utc0;
      halt = halt_iter;
    }
  }

  bool halt = false;

 private:
  std::vector<std::pair<int64_t, int64_t>> begin_end;
  int64_t today_utc0 = 0;
  int64_t current_time = 0;
};

}  // namespace coin2::strategy::linear_model
